package net.togogo.controller;

import net.togogo.bean.User;
import net.togogo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
public class UserController {

    @Autowired (required = false)
    UserService userService;

    @RequestMapping(value = "/regist",method = RequestMethod.POST)
    public String inserUser(User user){
        userService.inserUser(user);
        return "/login.jsp";
    }

    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public String login(User user,Model model){
        User u = userService.login(user);
        model.addAttribute("user",u);
        System.out.println("u = " + u);
        if (u !=null){
            return "/list.do";
        }
        return "/login.jsp";
    }

    @RequestMapping("/list")
    public String listUser(Model model){
        List<User> users = userService.listUser();
        System.out.println("users = " + users);
        model.addAttribute("userList",users);
        return "/list.jsp";
    }

    @RequestMapping("id")
    public String selectById(@RequestParam("id") Integer id,Model model){
        User user = userService.selectById(id);
        System.out.println("user = " + user);
        model.addAttribute("userList",user);
        return "/list-id.jsp";
    }

    @RequestMapping("/update")
    public String updateUser(User user,Model model){
        int i = userService.updateUser(user);
        if (i > 0){
            List<User> list = userService.listUser();
            model.addAttribute("userList",list);
            return "/list.jsp";
        }
        return null;
    }

    @RequestMapping("/delete")
    public String deleteUserById(@RequestParam("id") Integer id,Model model){
        int user = userService.deleteUserById(id);
        if (user > 0){
            List<User> users = userService.listUser();
            model.addAttribute("userList",users);
            return "/list.jsp";
        }
        return null;
    }
}
